package com.cb.domain.service.file;

import java.awt.Rectangle; 
import java.awt.image.BufferedImage; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.InputStream; 
import java.util.Iterator; 

import javax.imageio.ImageIO; 
import javax.imageio.ImageReadParam; 
import javax.imageio.ImageReader; 
import javax.imageio.stream.ImageInputStream; 
import javax.servlet.http.HttpServletRequest;

public class CutImage { 
	// 图片源 
	
	private static final String SRC_FILE = "D:/dev34/taoletao/web/attachments/imgs/product/201007/005915593086589632xorg.jpg"; 
	
	// 目标图片 
	
	private static final String DEST_FILE = "D:/dev34/taoletao/web/attachments/imgs/product/201007/2.jpg"; 

public String readUsingImageReader(HttpServletRequest request,String filePath ,int left,int top,int width,int height) throws Exception{ 

// 取得图片读入器 
	
	Iterator readers = ImageIO.getImageReadersByFormatName("jpg"); 
	
	ImageReader reader = (ImageReader) readers.next(); 
	
// 取得图片读入流 
	String readeServerPath=request.getSession().getServletContext().getRealPath("/")
	+filePath;
	
	InputStream source = new FileInputStream(readeServerPath); 
	
	ImageInputStream iis = ImageIO.createImageInputStream(source); 
	
	reader.setInput(iis, true); 

// 图片参数 

ImageReadParam param = reader.getDefaultReadParam(); 

Rectangle rect = new Rectangle(left, top, width, height);//100，200是左上起始位置，300就是取宽度为300的，就是从100开始取300宽，就是横向100~400，同理纵向200~350的区域就取高度150 

param.setSourceRegion(rect); 

BufferedImage bi = reader.read(0, param); 

String cutPath=filePath.replace(FileUpload.IMG_SUFFIX_ORG, FileUpload.IMG_SUFFIX_SMALL);

String writeServerPath=request.getSession().getServletContext().getRealPath("/")
+cutPath;
ImageIO.write(bi, "jpg", new File(writeServerPath)); 

	return cutPath;
} 
	public static void main(String[] args) throws Exception{ //main方法测试用
		CutImage t =new CutImage(); 
//		t.readUsingImageReader(SRC_FILE,100,100,250,150); 
	} 
} 